<template>
  <div class="userheader">
    <div class="search">
      <span class="name">姓名</span>
      <el-input
        size="small"
        placeholder="姓名"
        suffix-icon="el-icon-date"
        v-model="searchMessage.userName">
      </el-input>
    </div>
    <div class="search">
      <span class="name">手机号</span>
      <el-input
        size="small"
        placeholder="手机号"
        suffix-icon="el-icon-date"
        v-model="searchMessage.userPhone">
      </el-input>
    </div>
    <div class="search">
      <span class="name">邮箱</span>
      <el-input
        size="small"
        placeholder="邮箱"
        suffix-icon="el-icon-date"
        v-model="searchMessage.userEmail">
      </el-input>
    </div>
    <div class="search-button">
      <el-button type="primary" size="small" @click="searchUser">查询</el-button>
        <el-button type="primary" size="small" v-for="role in roles" :key="role" v-if="role === 'admin'" @click="dialogFormVisible = true">新增用户</el-button>
    </div>
    <div>
      <el-dialog title="新增用户" :visible.sync="dialogFormVisible" style="width:80%;margin-left:10%">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" size="small">
          <el-form-item label="登录名" prop="code" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.code" ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" prop="name" :label-width="formLabelWidth" :rules="rules.name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="password" :label-width="formLabelWidth" :rules="rules.password">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="emailNumber" :label-width="formLabelWidth" :rules="rules.emailNumber">
            <el-input v-model="ruleForm.emailNumber"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber" :label-width="formLabelWidth" :rules="rules.phoneNumber">
            <el-input v-model="ruleForm.phoneNumber"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('ruleForm')" size="small">立即修改</el-button>
          <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { mapState,mapGetters } from 'vuex';
  import axios from 'axios';
  import QS from 'qs';

    export default {
      name: "userHeader",
      computed: {
        ...mapGetters([
          'name',
          'roles'
        ]),
        ...mapState([
          'conts',
          'userTableData',
        ]),
      },
      data(){
        return{
          dialogFormVisible: false,
          formLabelWidth: '80px',
          searchMessage: {
            userName: '',
            userPhone: '',
            userEmail: '',
          },
          ruleForm: {
            userid:'',
            code: '',
            name: '',
            password: '',
            emailNumber: '',
            phoneNumber: '',
            region: '',
          },
          rules: {
            code: [
              { required: true, message: '请输入登录名', trigger: 'blur' },
              { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
              { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号' }
            ],
            name: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },{
              min: 2,
              max: 5,
              message: '长度在 2 到 5 个字符'
            },{
              pattern: /^[\u4E00-\u9FA5]+$/,
              message: '用户名只能为中文'
            }
              //{ pattern:/^[a-zA-Z]w{1,4}$/, message: '以字母开头，长度在2-5之间， 只能包含字符、数字和下划线'}
            ],
            password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            }, {
              min: 6,
              max: 30,
              message: '长度在 6 到 30 个字符'
            }, {
              pattern: /^(\w){6,20}$/,
              message: '只能输入6-20个字母、数字、下划线'
            }],

            emailNumber: [
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输正确的邮箱地址', trigger: 'blur' }
            ],
            phoneNumber: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'blur'
            },
              {validator:function(rule,value,callback){
                  if(/^1[34578]\d{9}$/.test(value) == false){
                    callback(new Error("请输入正确的手机号"));
                  }else{
                    callback();
                  }
                }, trigger: 'blur'}
            ],
            //   pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
          }
        }
      },
      methods:{
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            const that = this;   //由于this指向已经不是 vue 的对象啦，所以必须重新对this进行定义。
            if (valid) {
              const userform = {};
              userform['userCode'] = this.ruleForm.code
              userform['userName'] = this.ruleForm.name;
              userform['userPwd'] = this.ruleForm.password;
              userform['userEmail'] = this.ruleForm.emailNumber;
              userform['userPhone'] = this.ruleForm.phoneNumber;
              userform['userGender'] = this.ruleForm.resource;
              axios.post('/api/sys/sysUser/addSysUser',QS.stringify(userform)) //使用QS对对象进行包裹
                .then(function (response) {
                  const data = response.data;
                  if (data.code == "200"){
                    that.searchMessage.userName = '';
                    that.searchMessage.userPhone = '';
                    that.searchMessage.userEmail = '';
                    that.searchUser();
                    alert('添加成功');
                    that.dialogFormVisible = false;
                    // that.$router.push({ path: '/user2' });
                  }else if (data.code == "500"){
                    if (data.errorMessage='用户编码不能重复'){
                      alert('登录名已存在，请重新输入登录名!');
                      that.ruleForm.code='';
                    }else{
                      alert(data.errorMessage);
                    }
                  }else{
                    alert('错误代码:' + data.code + '请联系系统管理员！')
                  }
                })
                .catch(function (error) {
                  console.log(error);
                });

            }else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        searchUser(){
          const that = this;
          const userMessage = {};
            userMessage['userName'] = this.searchMessage.userName;
            userMessage['userPhone'] = this.searchMessage.userPhone;
            userMessage['userEmail'] = this.searchMessage.userEmail;
          axios.post('/api/sys/sysUser/selectSysUser',QS.stringify(userMessage))
            .then(function (response) {
              const data = response.data;
              if (data.code == "200"){
                that.$store.commit('userTableList',data.data);  //通过commit操作store中mutations下的userTableList方法，完成对数组的赋值。
              }else if (data.code == "201") {
                alert(data.code + '您所查询的信息不存在！请重新输入!');
              }else{
                alert('错误代码:' + data.code + '请联系系统管理员！');
              };
            })
            .catch(function (error) {
              console.log(error);
            });
        }
      },
      mounted:function () {
        this.searchUser();
      }
    }

</script>

<style scoped>
  .userheader{
    float: left;
    margin-bottom: 15px;
  }
  .search{
    float: left;
    display: flex;
  }
  .search-button{
    float: left;
    margin-left: 10px;
  }
  .name{
    float: right;
    display: flex;
    width: 70px;
    margin-left: 10px;
    line-height: 32px;
    text-align: right;
    color: #1f2d3d;
    font-size: 14px;
  }
  .spanName{
    /*float: left;*/
    /*line-height: 32px;*/
    /*display: inline-block;*/
  }

</style>
